import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserStore } from '@/stores'
import {
  addToOrderAPI,
  addCartListAPI,
  getCartListAPI,
  deleteCartListAPI
} from '@/apis/cart'
import { ElMessage } from 'element-plus'

export const useCartStore = defineStore(
  'cart',
  () => {
    // 获取token
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)
    // 定义state
    const cartList = ref([])
    const updateCartList = async () => {
      if (!isLogin.value) return
      getCartListAPI(userStore.userInfo.data.userId)
        .then((res) => {
          cartList.value = res.rows[0]
        })
        .catch((error) => {
          console.error('获取购物车列表失败', error)
        })
    }
    // 定义action
    // 添加购物车
    const addCart = async (goods) => {
      const addCartList = ref({})
      addCartList.value.details = goods
      addCartList.value.userId = userStore.userInfo.data.userId

      // 判断是否登录
      if (isLogin.value) {
        // 登录之后加入购物车逻辑
        await addCartListAPI(addCartList).then((res) => {
          if (res.code === 200) {
            ElMessage.success('添加购物车成功')
            // 添加成功
            updateCartList()
          } else {
            // 添加失败
            ElMessage.error('添加购物车失败')
          }
        })
      } else {
        // 未登录
        const item = cartList.value.find((item) => goods.skuId === item.skuId)
        // 如果已添加过
        if (item) {
          item.count += goods.count
        } else {
          // 如果没添加
          cartList.value.push(goods)
        }
      }
    }
    // 删除购物车商品
    const deleteCart = async (cartDetailsId) => {
      if (isLogin.value) {
        await deleteCartListAPI([cartDetailsId])
        updateCartList()
      } else {
        const idx = cartList.value.details.findIndex(
          (item) => cartDetailsId === item.cartDetailsId
        )
        cartList.value.details.splice(idx, 1)
      }
    }
    // 购物车逻辑添加到订单
    const addToOrder = async (data) => {
      //只保留data的cartDetailsID 和 toOrder属性
      console.log(data)

      await addToOrderAPI(data)
    }
    // 计算总数
    const allCount = computed(() => {
      // 判断是否登录
      if (!cartList.value.details) return 0
      return cartList.value.details.reduce((pre, item) => {
        return pre + item.productQuantity
      }, 0)
    })
    // 计算总价
    const allPrice = computed(() => {
      // 判断是否登录
      if (!cartList.value.details) return 0
      return cartList.value.details.reduce((pre, item) => {
        return pre + item.productPrice * item.productQuantity
      }, 0)
    })
    // 单选功能
    const singleCheck = (cartDetailsId, selected) => {
      const item = cartList.value.details.find(
        (item) => item.cartDetailsId === cartDetailsId
      )
      if (item) {
        item.selected = selected
      }
    }
    // 全选功能
    const allCheck = (selected) => {
      cartList.value.details.forEach((item) => {
        item.selected = selected
      })
    }
    // 是否全选计算属性
    const isAll = computed(() => {
      if (!cartList.value.details) return false
      return cartList.value.details.every((item) => item.selected)
    })
    // 购物车勾选数量
    const selectedCount = computed(() => {
      if (!cartList.value.details) return 0
      //把details里面selected属性为1的数量计算返回
      return cartList.value.details.reduce((pre, item) => {
        return pre + (item.selected ? item.productQuantity : 0)
      }, 0)
    })
    // 购物车勾选总价
    const selectedPrice = computed(() => {
      if (!cartList.value.details) return 0
      return cartList.value.details
        .filter((item) => item.selected)
        .reduce((pre, item) => {
          return pre + item.productPrice * item.productQuantity
        }, 0)
    })
    // 改变商品数量
    const changeCount = (cartDetailsId, productQuantity) => {
      const item = cartList.value.details.find(
        (item) => item.cartDetailsId === cartDetailsId
      )
      if (item) {
        item.productQuantity = productQuantity
      }
    }
    // 清空购物车
    const clearCart = () => {
      cartList.value = []
    }
    return {
      addCart,
      cartList,
      deleteCart,
      allCount,
      addToOrder,
      allPrice,
      singleCheck,
      allCheck,
      isAll,
      selectedCount,
      selectedPrice,
      changeCount,
      clearCart,
      updateCartList
    }
  },
  { persist: true }
)
